#! /usr/bin/python
# -*- coding: cp1250 -*-

import glob, sys, os, re, string
import pepe.p_txt.bigtxt as bt

def srchr(filesmask, search, replace, re_scope='per-line', ofile='_srchr.#'):
    '''
    Purpose: Search and replace in txt files using regex.
    Usage: srchr.py <file mask> <search string> <replace string> [per-file]
    Example: srchr.py *.csv \"^ALFA\" \"^BETA\" per-file
    '''
    of = open(ofile, 'w')
    
    for infile in glob.glob(filesmask):

        if re_scope == 'per-line':
            for line in bt.lines(infile):
                line = re.sub(search, replace, line)
                of.write(line)
        else:
            inp_file = open(infile,'r')
            inp_data = inp_file.read()
            inp_data = re.sub(search, replace, inp_data)
            inp_file.close()
            of.write(inp_data)

    of.close()

if __name__ == '__main__':
    if len(sys.argv) == 4:
        srchr(sys.argv[1], sys.argv[2], sys.argv[3])
    elif len(sys.argv) == 5:
        srchr(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
    else:
        print srchr.__doc__
